<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Lite;

use App\Api\Controllers\BaseController;
use App\Models\Device;
use App\Models\DeviceServiceProviders;
use App\Models\Store;
use App\Models\User;
use App\Traits\ResponseTrait;
use App\Util\ListUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ProviderController extends BaseController
{
    use ResponseTrait;

    //添加服务商
    public function addProvider(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $data = $request->all();
            $validator = Validator::make($data,
                [
                    "name" => ["required", "string"],
//                    "merchant_id" => ["required"],
                    "pid" => ["required",],
                    "app_id" => ["required"]
                ],
                [
                    "device_no.unique" => "设备号已经存在"
                ],
                [
                    "name" => "服务商名称",
//                    "merchant_id" => "商户ID",
                    "pid" => "服务商PID",
                    "app_id" => "服务商应用APPID",
                ]
            );
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            //检测是否重复
            $exists = DeviceServiceProviders::query()->where(["pid" => $data["pid"], "app_id" => $data["app_id"]])->exists();
            if ($exists) {
                throw new \Exception($data["name"] . "_服务商的PID和应用的APPID已经被使用");
            }

//            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
//            $systemUserArray = ListUtil::createListsNode($systemUserArray);
//            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
//            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
//            $userCollectionIds = array_column($userCollection, "id");
//
//            $store = Store::query()->where("store_id", $data["store_id"])->whereIn("user_id", $userCollectionIds)->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
//            $store = Store::query()->where("store_id", $data["store_id"])->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
            $deviceProvider = DeviceServiceProviders::query()->create([
                "name" => $data["name"],
                "pid" => $data["pid"],
                "app_id" => $data["app_id"],
                "is_auth" => 0,
                "user_id" => $user->user_id
            ]);
            if (empty($deviceProvider)) {
                throw new \Exception("服务商添加失败");
            }
            return $this->successResponse("ok", ["data" => $deviceProvider->toArray()]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //更新服务商
    public function upProvider(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $provider_id = $request->post("provider_id");
            $data = $request->all();
            $validator = Validator::make($data,
                [
                    "name" => ["required", "string"],
//                    "merchant_id" => ["required"],
                    "pid" => ["required",],
                    "app_id" => ["required"]
                ],
                [
                    "device_no.unique" => "设备号已经存在"
                ],
                [
                    "name" => "服务商名称",
//                    "merchant_id" => "商户ID",
                    "pid" => "服务商PID",
                    "app_id" => "服务商应用APPID",
                ]
            );
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            //检测是否重复
            $exists = DeviceServiceProviders::query()->where(["pid" => $data["pid"], "app_id" => $data["app_id"]])->where("id", "!=", $provider_id)->exists();
            if ($exists) {
                throw new \Exception($data["name"] . "_服务商的PID和应用的APPID已经被使用");
            }

            $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
            $systemUserArray = ListUtil::createListsNode($systemUserArray);
            $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
            $userCollection = ListUtil::listsNodeToArray([$userCollection]);
            $userCollectionIds = array_column($userCollection, "id");
//
//            $store = Store::query()->where("store_id", $data["store_id"])->whereIn("user_id", $userCollectionIds)->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
//            $store = Store::query()->where("store_id", $data["store_id"])->first();
//            if (empty($store)) {
//                throw new \Exception("店铺不存在");
//            } else if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
//                throw new \Exception("店铺已经关闭");
//            }
            $deviceProvider = DeviceServiceProviders::query()->where("id", $provider_id)->whereIn("user_id", $userCollectionIds)->first();
            if (empty($deviceProvider)) {
                throw new \Exception("服务商不存在");
            } else if ($deviceProvider->is_auth == 1) {
                throw new \Exception("服务商已经授权，无法编辑");
            }

            $deviceProvider->name = $data["name"];
            $deviceProvider->pid = $data["pid"];
            $deviceProvider->app_id = $data["app_id"];
            $deviceProvider->save();
            return $this->successResponse("ok", ["data" => $deviceProvider->toArray()]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    //删除服务商
    public function delProvider(Request $request): string
    {
        $provider_id = $request->post("provider_id");

        $provider = DeviceServiceProviders::query()->where("id", $provider_id)->first();

        if (empty($provider)) {
            return $this->errorResponse("服务商不存在");
        } else if ($provider->is_auth == 1) {
            return $this->errorResponse("服务商已经授权，无法删除");
        }

        $provider->delete();
        return $this->successResponse("ok");
    }

    //服务商列表
    public function listProvider(Request $request): string
    {
        $page = $request->get("page", 1);
        $pagesize = $request->get("pagesize", 10);

        $where = [
            "name" => $request->get("name"),
            "is_auth" => $request->get("is_auth")
        ];

        $user = $this->parseToken();
        $systemUserArray = User::query()->select("id", "pid", "name")->get()->toArray();
        $systemUserArray = ListUtil::createListsNode($systemUserArray);
        $userCollection = ListUtil::getListsNode($systemUserArray, ["id" => $user->user_id]);
        $userCollection = ListUtil::listsNodeToArray([$userCollection]);
        $userCollectionIds = array_column($userCollection, "id");

        $query = DeviceServiceProviders::query()
            ->select(["id",
                "name",
                "pid",
                "app_id",
                "is_auth",
//                "user_id",
//                "app_auth_code",
//                "app_auth_token",
                "created_at",
                "updated_at",
            ])
//                ->whereIn("store_id", $store_ids)
            ->where(function ($query) use ($where) {
                if (!empty($where["name"])) {
                    $query->where("name", "like", "%" . $where["name"] . "%");
                }
                if (isset($where["is_auth"]) && $where["is_auth"] > -1) {
                    $query->where("is_auth", $where["is_auth"]);
                }
            })
            ->whereIn("user_id", $userCollectionIds);

        $total = (clone $query)->count();
        $lists = $query->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->toArray();
        $data = [
            "data" => $lists,
            "total" => $total
        ];
        return $this->successResponse("ok", $data);

    }


    public function listProviderSelect(Request $request): string
    {
        $lists = DeviceServiceProviders::query()
            ->select(["id",
                "name",
                "pid",
                "app_id",
                "is_auth",
//                "user_id",
//                "app_auth_code",
//                "app_auth_token",
                "created_at",
                "updated_at",
            ])
            ->where("is_auth", 1)
            ->get()
            ->toArray();
        $data = [
            "data" => $lists,
        ];
        return $this->successResponse("ok", $data);

    }


}